//
//  CZNetworkTool.m
//  XinLang_OC
//
//  Created by WONG on 16/2/21.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "CZNetworkTool.h"
#import "CZUserAccount.h"

/**
 *  错误编号
 */
typedef enum {
    CZNetworkToolError_AccessToken = -1,// AccessToken没有值
    CZNetworkToolError_Uid = -2// uid没有值
}CZNetworkToolError;

@interface CZNetworkTool ()

@property (nonatomic,copy) NSString *access_token;
@property (nonatomic,copy) NSString *uid;


@end

@implementation CZNetworkTool

#pragma mark - singleton pattern
+ (instancetype)sharedHttpTool {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        // 不能转换text/plain类型，需要手动增加此类型
        NSMutableSet *set = [NSMutableSet setWithSet:[instance responseSerializer].acceptableContentTypes];
        [set addObject:@"text/plain"];
        [instance responseSerializer].acceptableContentTypes = set;
    });
    return instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
        // 不能转换text/plain类型，需要手动增加此类型
        NSMutableSet *set = [NSMutableSet setWithSet:[instance responseSerializer].acceptableContentTypes];
        [set addObject:@"text/plain"];
        [instance responseSerializer].acceptableContentTypes = set;
    });
    return instance;
}

#pragma mark -

- (NSURL *)oauthURL {
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",client_id,redirect_uri];
    return [NSURL URLWithString:urlStr];
}

- (void)loadAccessToken:(NSString *)code finished:(void (^)(id reposponseObject, NSError *error))finished {
    NSString *urlStr = @"https://api.weibo.com/oauth2/access_token";
    
    // 请求参数
    NSDictionary *parameters = @{@"client_id": client_id, @"client_secret": client_secret, @"grant_type": @"authorization_code", @"code": code, @"redirect_uri": redirect_uri};
    
    [self POST:urlStr parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        finished(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil,error);
    }];
}

/**
 *  获取用户数据
 */
- (void)loadUserInfo:(void (^)(id result, NSError *error))finished {
    if (!self.access_token) {
        //NSLog(@"access_token");
        NSError *error = [NSError errorWithDomain:@"cz.itcast.error.net" code:CZNetworkToolError_AccessToken userInfo:@{@"description": @"access_token没有值"}];
        finished(nil, error);
        return;
    }
    if (!self.uid) {
        NSError *error = [NSError errorWithDomain:@"cz.itcast.error.net" code:CZNetworkToolError_Uid userInfo:@{@"description": @"uid没有值"}];
        finished(nil, error);
        return;
    }
    
    NSString *urlStr = @"https://api.weibo.com/2/users/show.json";
    
    NSDictionary *prameters = @{@"access_token": self.access_token, @"uid": self.uid};
    
    [self GET:urlStr parameters:prameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil, error);
    }];
}
/**
 *  加载微博数据
 */
- (void)loadStatus:(void (^)(id result, NSError *error))finished {
    if (!self.access_token) {
        //NSLog(@"access_token");
        NSError *error = [NSError errorWithDomain:@"cz.itcast.error.net" code:CZNetworkToolError_AccessToken userInfo:@{@"description": @"access_token没有值"}];
        finished(nil, error);
        return;
    }

    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSDictionary *parameters = @{@"access_token": self.access_token};
    [self GET:urlStr parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(error, nil);
    }];
    
    [self POST:@"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

/**
 *  加载微博数据
 *  - parameter since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
 *  - parameter max_id:   若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
 *  - parameter finished: 网络请求完毕的回调
 */
- (void)loadStatus:(NSNumber *)since_id max_id:(NSNumber *)max_id finished:(void(^)(id result, NSError *error))finished {
    if (!self.access_token) {
        //NSLog(@"access_token");
        NSError *error = [NSError errorWithDomain:@"cz.itcast.error.net" code:CZNetworkToolError_AccessToken userInfo:@{@"description": @"access_token没有值"}];
        finished(nil, error);
        return;
    }
    
    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.access_token forKey:@"access_token"];
    if (since_id > 0) { // 表示别人有传since_id,下拉刷新,才需要拼接
        [parameters setObject:since_id forKey:@"since_id"];
    } else if (max_id > 0) { // 表示别人有传max_id,上拉加载更多,才需要拼接
        [parameters setObject:@(max_id.longValue - 1) forKey:@"max_id"];// max_id - 1防止加载重复的数据
    }
    //NSLog(@"parameters = %@",parameters);
    [self GET:urlStr parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(error, nil);
    }];
}


/**
 抽取AFN GET / POST 方法,网络请求的统一入口都是这个方法
 
 - parameter requestMethod: 请求方式get post
 - parameter urlString:     url地址
 - parameter parameters:    参数
 - parameter finished:      回调的闭包
 */
//- (void)request:(NSString *)requesMethod urlString:(NSString *)urlString parameters:(id)parameters needAccessToken:(BOOL)needAccessToken finished:(NetworkCallback)finished{
//    // 需要accessToken,就拼接
//    if (needAccessToken) {
//        if (![CZUserAccount loadUserAccount].access_token) {
//            NSError *error = [NSError errorWithDomain:@"cz.itcast.error.net" code:CZNetworkToolError_AccessToken userInfo:@{@"description": @"access_token没有值"}];
//            finished(nil, error);
//            return;
//        }
//        parameters[@"access_token"] = self.access_token;
//    }
//    // 根据请求方式,发送对应的请求
//    if ([requesMethod isEqualToString:@"get"]) {
//        [self GET:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//            finished(responseObject, nil);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            finished(nil, error);
//        }];
//    }else if ([requesMethod isEqualToString:@"post"]) {
//        [self POST:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//            finished(responseObject, nil);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            finished(nil, error);
//        }];
//    }
//}




#pragma mark load lazy
- (NSString *)access_token {
    if (_access_token == nil) {
        _access_token = [CZUserAccount loadUserAccount].access_token;
    }
    return _access_token;
}
- (NSString *)uid {
    if (_uid == nil) {
        _uid = [CZUserAccount loadUserAccount].uid;
    }
    return _uid;
}


@end




















